package com.fhx.core.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager


class SoftKeyboardUtils {
    companion object {
        /**
         * 关闭软键盘
         *
         * @param activity 当前Activity
         */
        fun hide(activity: Activity?) {
            if (activity == null) return
            val view: View? = activity.window.peekDecorView()
            if (view != null) {
                val inputmanger: InputMethodManager =
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputmanger.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }

        /**
         * 强制显示软键盘
         *
         * @param activity 当前Activity
         */
        fun show(activity: Activity?) {
            if (activity == null) return
            val view: View? = activity.window.peekDecorView()
            if (view != null) {
                val inputmanger: InputMethodManager =
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                val isOpen: Boolean = inputmanger.isActive //isOpen若返回true，则表示输入法打开
//                if (!isOpen) {
                inputmanger.showSoftInput(view, InputMethodManager.SHOW_FORCED)
//                }
            }
        }

        /**
         * 输入法在窗口上已经显示，则隐藏，反之则显示
         *
         * @param activity 当前Activity
         */
        fun toggle(activity: Activity?) {
            if (activity == null) return
            val view: View? = activity.window.peekDecorView()
            if (view != null) {
                val inputmanger: InputMethodManager =
                    activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputmanger.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }
}